<template>
  <div class="approval-result">
    <!-- 右侧审批区域 -->
    <div v-if="role === 0" class="right-column"> <!-- 注意：原代码 v-if="!role" 可能逻辑反了，这里修正为 role === 0 -->
      <!-- 操作记录（保持不变） -->
      <el-card shadow="hover" class="record-card" style="margin-top: 20px;">
        <!-- 省略操作记录内容 -->
          <template #header>
          <div class="card-header">操作记录</div>
        </template>
        <el-timeline>
          <el-timeline-item
            v-for="(record, index) in operationRecords"
            :key="index"
            :timestamp="record.time"
            :type="record.type"
            :color="record.color"
            :icon="record.icon"
          >
            <p>{{ record.title }}</p>
            <p>{{ record.desc }}</p>
            <p v-if="record.opinion">审批意见：{{ record.opinion }}</p>
          </el-timeline-item>
        </el-timeline>
      </el-card>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, getCurrentInstance } from 'vue'; // 导入 getCurrentInstance
import { WarningFilled, DocumentDelete, User } from '@element-plus/icons-vue';
import { addAccraditationRecord, tuizhuaddAccraditationRecord } from '@/api/le/accraditationRecord';
import { useUserStore } from '@/store/modules/user'
import { listAccraditationRecord } from "@/api/le/accraditationRecord"

// 获取组件实例的 proxy
const { proxy } = getCurrentInstance(); // 新增这一行
const accraditationRecord = ref({});
const userStore = useUserStore()
// 角色（0：审批角色，显示表单）
const role = ref(0);
const props = defineProps({
  Lastfrom: {
    type: Object,
    required: true
  },
  shenpiform: {
    type: Object,
    required: true
  },
  currentStep: {
    type: String,
    required: true
  }

});

console.log("审批页面接受的pending",props.Lastfrom);

// 表单数据（用 reactive 统一管理）
const form = reactive({
  auditStatus: '', // 审批结果（1通过/2拒绝/3驳回）
  opinion: '', // 审批意见
  approverId: userStore.id,//操作人
  type:'',//业务类型
  bussniessId:'',//业务id
});
const Lastfrom = ref(props.Lastfrom)
// 表单 ref，用于调用验证方法
const approvalFormRef = ref(null);

// 子组件定义“提交表单”的方法（返回验证结果和表单数据）
const submitApprovalForm = () => {
  return new Promise((resolve, reject) => {
    // 调用 Element Plus 表单的验证方法
    approvalFormRef.value.validate((valid) => {
      if (valid) {
        // 验证通过，返回表单数据
        resolve({ ...form });
          form.handleType = Lastfrom.value.id
          form.extraField1 = Lastfrom.value.taskId
          form.bussniessId = Lastfrom.value.bussniessId
          form.extraField2 = Lastfrom.value.extraField2
          form.type  = Lastfrom.value.type
          form.createTime = Lastfrom.value.createTime
          form.createBy = Lastfrom.value.applicatId
          form.stepNo = Lastfrom.value.stepNo
          form.approverId = Lastfrom.value.assigneeId
          form.id = Lastfrom.value.id
         tuizhuaddAccraditationRecord(form).then(response => {
          proxy.$modal.msgSuccess("新增成功")
        })
        // console.log("创建人",form.createBy);
        
      } else {
        // 验证失败，返回错误信息
        reject(new Error('请完善审批信息'));
      }
    });
  });
};


//获取当前步骤对应的审批记录
const getAcc = ()=>{
  listAccraditationRecord({
      bussniessId: props.Lastfrom.bussniessId,
      stepNo: props.currentStep
    }).then(response => {
      const records = response.rows || [];
      console.log("res",response);
      accraditationRecord.value = records[0];
      console.log("审批页面获取的审批记录",accraditationRecord.value);
      changeMsg(); 
    }).catch(error => {
      console.error("获取审批记录失败：", error);
      role.value.roleId = 0;
    });
}
getAcc()

// 暴露 submitApprovalForm 方法给父组件
defineExpose({
  submitApprovalForm
});

// 操作记录数据（保持不变）
const operationRecords = ref([
  {
    title: '发起申请-申请退住',
    desc: '顾廷烨（已发起）',
    time: '2048-10-15 09:00:00',
    type: 'primary',
    color: '#6a7dfe',
    icon: DocumentDelete
  },
  {
    title: '（角色）审批-申请审批',
    desc: '盛明兰（审批中）',
    time: '',
    type: 'info',
    color: '#409EFF',
    icon: User
  }
]);
const changeMsg = ()=>{
  console.log("审批记录",props.shenpiform);
  operationRecords.value = [
{
    title: accraditationRecord.value.currentStep,
    desc: accraditationRecord.value.approverName+'（已审批）',
    time: accraditationRecord.value.createTime,
    type: 'primary',
    color: '#6a7dfe',
    icon: DocumentDelete
  },
  {
    title: accraditationRecord.value.nextStep,
  desc: accraditationRecord.value.nextApprover 
    ? `${accraditationRecord.value.nextApprover}（审批通过）` 
    : '审批完成',    time: '',
    type: 'info',
    color: '#409EFF',
    opinion: accraditationRecord.value.opinion,
    icon: User
  }
];
}

</script>
<style scoped>
.approval-result {
  max-width: 600px;
  /* margin: 20px auto; */

}
.approval-status {
  text-align: center;
  padding: 30px 0;
}
.status-icon {
  font-size: 40px;
  color: #909399;
  margin-bottom: 16px;
}
.operation-record {
  margin-top: 20px;
  background-color: #eaebed;
  padding: 30px;
}
.operation-record h5 {
  font-size: 16px;
  margin-bottom: 12px;
}
.showMessage{
    width: 100%;
    margin: 20px 350px;
}
.approval-page {
  display: flex;
  gap: 20px;
  padding: 20px;
}
.left-column, .right-column {
  flex: 1;
}
.info-card, .approval-card, .record-card {
  height: fit-content;
}
.card-header {
  font-size: 16px;
  font-weight: bold;
}
</style>